package com.dy.servlet;

import com.alibaba.fastjson.JSONObject;
import com.dy.domain.Admin;
import com.dy.mapper.AdminMapper;
import com.dy.utils.JsonResultUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/adminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    public AdminLoginServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码类型
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //获取账号和密码
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        JSONObject data = null;

        //1. 加载mybatis的核心配置文件，获取 SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象，用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.1 获取AdminMapper接口的代理对象
        AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
        Admin admin = adminMapper.loginVerify(account, password);

        if (admin != null){
            System.out.println("管理员");
            data = JsonResultUtil.getJson("1");
        }else{
            //没有找到对应的账号和密码，返回重新登录
            System.out.println("密码错误");
            data = JsonResultUtil.getJson(200, "1", "密码错误");
        }
        //4. 释放资源
        sqlSession.close();
        response.getWriter().print(data);

    }
}
